package com.example.myapplication;
// C:\Users\liuzc\Desktop\MyApplication3\app\src\main\java\com\example\myapplication\MainActivity.java

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private TextView tvQuestion;
    private EditText etInput;
    private Button btnSettings;
    private TextView tvStatus; // 新增：显示倒计时和得分
    private Button btnStart;    //开始游戏专用

    // 当前题目数据
    private int num1, num2;
    private char operator;
    private double correctAnswer;

    // 计分与计时
    private int score = 0;
    private int gameTimeInSeconds = 60; // 默认60秒
    private CountDownTimer countDownTimer;
    private boolean isGameRunning = false;

    // 按键数组（用于绑定事件）
    private int[] buttonIds = {
            R.id.btn_0, R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_4,
            R.id.btn_5, R.id.btn_6, R.id.btn_7, R.id.btn_8, R.id.btn_9,
            R.id.btn_plus, R.id.btn_minus, R.id.btn_multiply, R.id.btn_divide,
            R.id.btn_dot, R.id.btn_clear, R.id.btn_backspace, R.id.btn_enter
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        setupButtons();
//        newQuestion(); // 初始化第一道题
//        startGame();
    }

    private void initViews() {
        tvQuestion = findViewById(R.id.tv_question);
        etInput = findViewById(R.id.et_input);
        btnSettings = findViewById(R.id.btn_settings);
        tvStatus = findViewById(R.id.tv_status); //初始化新控件
        btnStart = findViewById(R.id.btn_start); // ✅ 初始化开始按钮

        // 禁用软键盘
        etInput.setKeyListener(null);
        etInput.setFocusable(true);
        etInput.setFocusableInTouchMode(true);

        btnSettings.setOnClickListener(v -> showSettingsDialog());

        // 绑定开始按钮点击事件
        btnStart.setOnClickListener(v -> {
            if (!isGameRunning) {
                startGame();
                newQuestion(); // 开始游戏后立即出题
            }
        });
    }

    private void setupButtons() {
        View.OnClickListener listener = v -> {
            Button b = (Button) v;
            String text = b.getText().toString();

            switch (text) {
                case "C":
                    etInput.setText("");
                    break;
                case "⌫":
                    String current = etInput.getText().toString();
                    if (!current.isEmpty()) {
                        etInput.setText(current.substring(0, current.length() - 1));
                    }
                    etInput.setSelection(etInput.getText().length()); // 光标移到末尾
                    break;
                case "Enter":
                    checkAnswer();
                    break;
                default:
                    etInput.append(text.replace("×", "*").replace("÷", "/")); // 显示友好，内部可用*
                    break;
            }
        };

        for (int id : buttonIds) {
            findViewById(id).setOnClickListener(listener);
        }
    }

    private void newQuestion() {
        Random rand = new Random();
        num1 = rand.nextInt(20) + 1; // 1-20
        num2 = rand.nextInt(20) + 1;

        int op = rand.nextInt(4);
        switch (op) {
            case 0:
                operator = '+';
                correctAnswer = num1 + num2;
                break;
            case 1:
                operator = '-';
                correctAnswer = num1 - num2;
                break;
            case 2:
                operator = '×';
                correctAnswer = num1 * num2;
                break;
            case 3:
                operator = '÷';
                // 确保整除
                num2 = rand.nextInt(10) + 1;
                num1 = num2 * rand.nextInt(10);
                correctAnswer = (double) num1 / num2;
                break;
            default:
                operator = '+';
                correctAnswer = num1 + num2;
        }

        tvQuestion.setText(num1 + " " + operator + " " + num2 + " = ?");
        etInput.setText("");
    }

    private void checkAnswer() {
        String inputStr = etInput.getText().toString().trim();
        if (inputStr.isEmpty()) return;

        try {
            double userAnswer = Double.parseDouble(inputStr);
            if (Math.abs(userAnswer - correctAnswer) < 0.01) { // 容差比较浮点
                score++;
                Toast.makeText(this, "✅ 正确！", Toast.LENGTH_SHORT).show();
                newQuestion();
            } else {
                Toast.makeText(this, "❌ 错了！正确答案是: " + correctAnswer, Toast.LENGTH_SHORT).show();
                newQuestion();
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效数字！", Toast.LENGTH_SHORT).show();
        }
    }

    private void startGame() {
        isGameRunning = true;
        score = 0;

        if (countDownTimer != null) countDownTimer.cancel();

        // 更新状态栏
        tvStatus.setText("⏱️ " + gameTimeInSeconds + "s | 得分: 0");

        // ❌ 禁用开始按钮，变灰
        btnStart.setEnabled(false);
        btnStart.setText("进行中...");
        btnStart.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

        countDownTimer = new CountDownTimer(gameTimeInSeconds * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int secondsLeft = (int) (millisUntilFinished / 1000);
                tvStatus.setText("⏱️ " + secondsLeft + "s | 得分: " + score);
            }

            @Override
            public void onFinish() {
                isGameRunning = false;
                tvStatus.setText("🎮 游戏结束！最终得分: " + score);

                // ✅ 游戏结束，重新启用“开始”按钮
                btnStart.setEnabled(true);
                btnStart.setText("开始");
                btnStart.setBackgroundColor(getColor(android.R.color.holo_blue_dark));
                Toast.makeText(MainActivity.this, "游戏结束，得分：" + score, Toast.LENGTH_LONG).show();
            }
        }.start();
    }

    private void showSettingsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("游戏设置");

        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_settings, null);
        builder.setView(dialogView);

        TextView tvTime = dialogView.findViewById(R.id.tv_time);
        Button btnMinus = dialogView.findViewById(R.id.btn_minus);
        Button btnPlus = dialogView.findViewById(R.id.btn_plus);
        Button btnContinue = dialogView.findViewById(R.id.btn_continue);
        Button btnExit = dialogView.findViewById(R.id.btn_exit);

        tvTime.setText(String.valueOf(gameTimeInSeconds));

        btnMinus.setOnClickListener(v -> {
            if (gameTimeInSeconds > 10) {
                gameTimeInSeconds -= 10;
                tvTime.setText(String.valueOf(gameTimeInSeconds));
            }
        });

        btnPlus.setOnClickListener(v -> {
            if (gameTimeInSeconds < 300) {
                gameTimeInSeconds += 10;
                tvTime.setText(String.valueOf(gameTimeInSeconds));
            }
        });

        final AlertDialog dialog = builder.create();

        btnContinue.setOnClickListener(v -> {
            dialog.dismiss();
            if (!isGameRunning) {
                startGame();
            }
        });

        btnExit.setOnClickListener(v -> {
            dialog.dismiss();
            finish(); // 退出应用
        });

        dialog.show();
    }

    @Override
    protected void onDestroy() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        super.onDestroy();
    }
}